package market

import (
	"go_server/game_server/dao/daily_dao"
	"go_server/game_server/dataconfig/config_manager"
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/zinx/ziface"
	"go_server/zinx/zlog"
	"go_server/zinx/znet"
	"time"
)

type MarketShowApi struct {
	znet.BaseRouter
}

// 商店显示
func (*MarketShowApi) Handle(request ziface.IRequest) {
	msg := &pb.MarketShowC2S{}
	if !util.PBParseRet(request, msg) {
		return
	}

	conn := request.GetConnection()
	roleId := ServiceObj.GetRoleId(request)

	// 获取商店商品配置
	baseItemList := config_manager.GetStcTableShop_SheetShopListByWeek(UN_LIMIT_TIMES_ITEM_TYPE)

	// 获取本周的第一天（周一）
	weekStartKey := time.Now().AddDate(0, 0, -int(time.Now().Weekday())+1).Format("20060102")
	row := daily_dao.GetDailyByDateKey(weekStartKey, roleId, []string{"market_item_info"})

	marketItemInfo := make(map[int32]int32)

	if row != nil && row.MarketItemInfo.Data() != nil {
		marketItemInfo = row.MarketItemInfo.Data()
	}

	itemList := make(map[int32]int32)

	if len(baseItemList) > 0 {
		for id, item := range baseItemList {
			limitBuyTimes := item.Buynumber // 限购次数

			useTime, exist := marketItemInfo[id]
			if exist {
				if useTime > limitBuyTimes {
					useTime = limitBuyTimes
				}
			} else {
				useTime = 0
			}

			itemList[id] = limitBuyTimes - useTime // 剩余购买次数
		}
	}

	// 计算下周一的时间
	nextMonday := time.Now().AddDate(0, 0, -int(time.Now().Weekday())+8)
	// 获取下周一的零点时间
	nextMondayStart := time.Date(nextMonday.Year(), nextMonday.Month(), nextMonday.Day(), 0, 0, 0, 0, nextMonday.Location())

	res := &pb.MarketShowS2C{
		Vip:         0,
		RefreshTime: nextMondayStart.UnixMilli(), // 获取下周一零点的时间戳
		ItemList:    itemList,
	}

	zlog.Infof("res=%v", res)

	// 优先返回下行
	conn.SendBuffPBMsg(uint32(pb.ProtocolManager_marketShow), res)
}
